<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\ParticipantActivity;
use App\Models\Animation;
use App\Models\AnimationCategory;
use App\Models\Play;
use App\Models\Section;
use App\Org\Developer\Helper;
use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use DB;
use Exception;

class PlayController extends Controller
{
    /**
     * @SWG\Get(
     *     summary="剧本列表",
     *     path="/play",
     *     description="获取用户的剧本列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码[default:1]",
     *         required=false,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="per_page",
     *         in="query",
     *         description="每页条数[default:15]",
     *         required=false,
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param Request $request
     *
     * @return array
     */
    public function index(Request $request)
    {
        $perPage = intval($request->get('per_page'));

        $paginate = Play::where(['user_id' => $request->user()->id])->orWhere(['is_share' => 1])
        // $paginate = Play::where(['user_id' => 1])->orWhere(['is_share' => 1])
            ->orderBy('id', 'desc')
            ->paginate($perPage, ['id', 'title', 'first_image', 'description', 'thumb', 'logo', 'page_turn_way', 'is_cycle', 'is_auto', 'is_template', 'is_share', 'music_url', 'counts', 'qrcode_image_url', 'wx_share_image']);

        // 如果没有参与者参加 play， 那么这个play 下不显示下载
        foreach ($paginate->items() as $item) {
            $counts = ParticipantActivity::where(['play_id' => $item['id']])->count();
            $item->hasParticipants = ($counts > 0 ) ? 1 : 0;
        }

        return $paginate;
    }

    /**
     * @SWG\Post(
     *     summary="创建剧本",
     *     path="/play",
     *     description="用户创建剧本",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="title",
     *         in="query",
     *         description="剧本标题",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="category_id",
     *         in="query",
     *         description="剧本分类",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="logo",
     *         in="query",
     *         description="是否有logo",
     *         required=false,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="page_turn_way",
     *         in="query",
     *         description="翻页方式(default:1)",
     *         required=false,
     *         type="integer",
     *         default=1
     *     ),
     *     @SWG\Parameter(
     *         name="is_cycle",
     *         in="query",
     *         description="循环播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default=0
     *     ),
     *     @SWG\Parameter(
     *         name="is_auto",
     *         in="query",
     *         description="自动播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default=0
     *     ),
     *     @SWG\Parameter(
     *         name="sections",
     *         in="query",
     *         description="章节数据(json格式):必要参数title[标题], sequence[顺序], css, properties",
     *         required=false,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param Request $request
     *
     * @return array;
     */
    public function store(Request $request)
    {
        $rules = [
            'title' => ['required', 'max:50'],
            'category_id' => ['required', 'exists:play_categories,id'],
            'page_turn_way' => ['required'],
            'is_cycle' => ['in:0,1'],
            'is_auto' => ['in:0,1'],
            'is_share' => ['in:0,1'],
            'sections' => ['json'],
        ];
        // $payload = $request->only('title', 'description', 'category_id', 'page_turn_way', 'is_cycle', 'is_auto', 'is_template', 'is_share', 'sections');
        $messages = [
            'title.required' => '请填写标题',
            'category_id.required' => '请选择剧本类型',
            'category_id.exists' => '剧本类型异常',
            'page_turn_way.required' => '请选择翻页方式',
            'is_cycle.in' => '循环播放异常',
            'is_auto.in' => '自动播放异常',
            'is_share.in' => '是否共享异常',
            'is_template.in' => '自动播放异常',
            'sections.json' => '元件数据异常'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            throw new StoreResourceFailedException('create error', $validator->errors());
        }

        $response = [];

        DB::beginTransaction();
        try {
            $play = new Play;

            $play->user_id = $request->user()->id;

            $play->title = $request->title;
            $response['title'] = $play->title;

            if (isset($request->description)) {
                $play->description = $request->description;
                $response['description'] = $play->description;
            }

            $play->category_id = $request->category_id;
            $response['category_id'] = $play->category_id;

            if (isset($request->logo)) {
                $play->logo = $request->logo;
                $response['logo'] = $play->logo;
            }

            if (isset($request->page_turn_way)) {
                $play->page_turn_way = $request->page_turn_way;
                $response['page_turn_way'] = $play->page_turn_way;
            }

            if (isset($request->is_cycle)) {
                $play->is_cycle = $request->is_cycle;
                $response['is_cycle'] = $play->is_cycle;
            }

            if (isset($request->is_auto)) {
                $play->is_auto = $request->is_auto;
                $response['is_auto'] = $play->is_auto;
            }

            if (isset($request->is_share)) {
                $play->is_share = $request->is_share;
                $response['is_share'] = $play->is_share;
            }

            if (isset($request->music_url)) {
                $play->music_url = $request->music_url;
                $response['music_url'] = $play->music_url;
            }

            if (isset($request->is_template)) {
                $play->is_template = $request->is_template;
                $response['is_template'] = $play->is_template;
            }
            $sectionData = json_decode($request->sections, true);

            if ($sectionData && isset($sectionData[0]['properties']['src'])) {
                $play->first_image = $sectionData[0]['properties']['src'];
            }
            $play->save();

            foreach ($sectionData as $data) {
                $section = new Section;

                $responseSection = [];
                $section->play_id = $play->id;

                if (isset($data['name'])) {
                    $section->name = $data['name'];
                    $responseSection['name'] = $section->name;
                }
                $section->num = $data['num'];
                $responseSection['num'] = $section->num;

                $section->properties = json_encode($data['properties']);
                $responseSection['properties'] = $section->properties;

                $section->elements = json_encode($data['elements']);
                $responseSection['elements'] = $section->elements;

                $section->save();
                $responseSection['id'] = $section->id;
                $response['sections'][] = $responseSection;
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw new StoreResourceFailedException('create error', $validator->errors());
        }

        // 生成该 play 的二维码图片，便于分享
        $qrcodeImagePath = \App\Org\Developer\Helper::makeQrcodeImage('http://thearte.jumpcity.cn/view?id=' . $play->id);
        $play->qrcode_image_url = $qrcodeImagePath;
        $play->save();
        // $result = 
        // if (!$result) {
        //     return JsonReturnInfo::infoFailure('创建失败.');
        // }
        $response['qrcode_image_url'] = $qrcodeImagePath;

        return ['status_code' => 200, 'data' => ['id' => $play->id, 'play' => $response]];
    }

    /**
     * @SWG\Get(
     *     summary="剧本详情",
     *     path="/play/{id}",
     *     description="用户剧本详情",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="id",
     *         in="path",
     *         description="剧本id",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param $id
     *
     * @return array
     */
    public function show($id)
    {
        $play = Play::findOrFail($id, ['id', 'category_id', 'title', 'description', 'first_image', 'logo', 'page_turn_way', 'is_cycle', 'is_auto', 'is_template', 'is_share', 'music_url', 'wx_share_title', 'wx_share_image', 'wx_share_description'])->toArray();
        $sections = Section::where(['play_id' => $id])->get(['id', 'name', 'num', 'properties', 'elements'])->toArray();
        $handleSections = [];
        foreach ($sections as $section) {
            $handleSections[] = [
                'id' => $section['id'],
                'name' => $section['name'],
                'num' => $section['num'],
                'properties' => json_decode($section['properties'], true),
                'elements' => json_decode($section['elements'], true)
            ];
        }

        $play['sections'] = $handleSections;

        return ['status_code' => 200, 'data' => $play];
    }

    /**
     * @SWG\Put(
     *     summary="修改剧本",
     *     path="/play/{id}",
     *     description="用户修改剧本",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="id",
     *         in="path",
     *         description="剧本id",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="name",
     *         in="query",
     *         description="剧本名称",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="category_id",
     *         in="query",
     *         description="剧本分类",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="page_turn_way",
     *         in="query",
     *         description="翻页方式(default:1)",
     *         required=false,
     *         type="integer",
     *         default="1"
     *     ),
     *     @SWG\Parameter(
     *         name="is_cycle",
     *         in="query",
     *         description="循环播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default="0"
     *     ),
     *     @SWG\Parameter(
     *         name="is_auto",
     *         in="query",
     *         description="自动播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default="0"
     *     ),
     *    @SWG\Parameter(
     *         name="sections",
     *         in="query",
     *         description="章节数据(json格式):必要参数id, title[标题], sequence[顺序], css, properties",
     *         required=false,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param Request $request
     * @param $id
     *
     * @return array
     */
    public function update_play(Request $request)
    {
        $rules = [
            'title' => ['required', 'max:50'],
            'category_id' => ['required', 'exists:play_categories,id'],
            'page_turn_way' => ['required'],
            'is_cycle' => ['in:0,1'],
            'is_auto' => ['in:0,1'],
            'is_share' => ['in:0,1'],
            'sections' => ['json'],
        ];
        //  $payload = $request->only('title', 'description', 'category_id', 'page_turn_way', 'is_cycle', 'is_auto', 'is_template', 'is_share', 'sections');
        $messages = [
            'title.required' => '请填写标题',
            'category_id.required' => '请选择剧本类型',
            'category_id.exists' => '剧本类型异常',
            'page_turn_way.required' => '请选择翻页方式',
            'is_cycle.in' => '循环播放异常',
            'is_auto.in' => '自动播放异常',
            'is_share.in' => '是否共享异常',
            'is_template.in' => '自动播放异常',
            'sections.json' => '元件数据异常'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            throw new StoreResourceFailedException('update error', $validator->errors());
        }

        DB::beginTransaction();
        try {
            $response = [];

            $user_id = $request->user()->id;
            $play_id = $request->id;

            $play = Play::findOrFail($play_id);
            // 更新操作
            if (isset($play) && $play->id && ($user_id == $play->user_id)) {
                $play->title = $request->title;
                $response['title'] = $play->title;

                if (isset($request->description)) {
                    $play->description = $request->description;
                    $response['description'] = $play->description;
                }

                $play->category_id = $request->category_id;
                $response['category_id'] = $play->category_id;

                if (isset($request->logo)) {
                    $play->logo = $request->logo;
                    $response['logo'] = $play->logo;
                }

                if (isset($request->page_turn_way)) {
                    $play->page_turn_way = $request->page_turn_way;
                    $response['page_turn_way'] = $play->page_turn_way;
                }

                if (isset($request->is_cycle)) {
                    $play->is_cycle = $request->is_cycle;
                    $response['is_cycle'] = $play->is_cycle;
                }

                if (isset($request->is_auto)) {
                    $play->is_auto = $request->is_auto;
                    $response['is_auto'] = $play->is_auto;
                }

                if (isset($request->is_share)) {
                    $play->is_share = $request->is_share;
                    $response['is_share'] = $play->is_share;
                }

                if (isset($request->is_template)) {
                    $play->is_template = $request->is_template;
                    $response['is_template'] = $play->is_template;
                }

                if (isset($request->music_url)) {
                    $play->music_url = $request->music_url;
                    $response['music_url'] = $play->music_url;
                }

                $sectionData = json_decode($request->sections, true);

                // 微信分享标题
                if (isset($request->wx_share_title)) {
                    $play->wx_share_title = $request->wx_share_title;
                }
                // 微信分享图片
                if (isset($request->wx_share_image)) {
                    $play->wx_share_image = $request->wx_share_image;
                }
                // 微信分享描述
                if (isset($request->wx_share_description)) {
                    $play->wx_share_description = $request->wx_share_description;
                }

                if ($sectionData && isset($sectionData[0]['properties']['src'])) {
                    $play->first_image = $sectionData[0]['properties']['src'];
                }
                $play->save();

                // 循环获取此次提交的所有id
                $sectionIds = [];
                foreach ($sectionData as $sectionItem) {
                    if (isset($sectionItem['id'])) {
                        $sectionIds[] = $sectionItem['id'];
                    }
                }

                // 获取所有sections
                $allSections = Section::where(['play_id' => $play->id])->get(['id'])->toArray();
                // 删除不存在的section
                if (!empty($allSections)) {
                    foreach ($allSections as $allSection) {
                        if (!in_array($allSection['id'], $sectionIds)) {
                            Section::where(['id' => $allSection['id']])->delete();
                        }
                    }
                }

                foreach ($sectionData as $data) {
                    if (isset($data['id'])) {
                        $section = Section::where(['id' => $data['id'], 'play_id' => $play->id])->first();
                    } else {
                        $section = new Section;
                    }

                    $responseSection = [];
                    $section->play_id = $play->id;
                    if (isset($data['name'])) {
                        $section->name = $data['name'];
                        $responseSection['name'] = $section->name;
                    }
                    $section->num = $data['num'];
                    $responseSection['num'] = $section->num;

                    $section->properties = json_encode($data['properties']);
                    $responseSection['properties'] = $section->properties;

                    $section->elements = json_encode($data['elements']);
                    $responseSection['elements'] = $section->elements;

                    $section->save();

                    $responseSection['id'] = $section->id;
                    $response['sections'][] = $responseSection;
                }
            }
            // 新增操作
            else {
                $play = new Play();

                $play->user_id = $user_id;
                $play->views = '0';

                $play->title = $request->title;
                $response['title'] = $play->title;

                if (isset($request->description)) {
                    $play->description = $request->description;
                    $response['description'] = $play->description;
                }

                $play->category_id = $request->category_id;
                $response['category_id'] = $play->category_id;

                if (isset($request->logo)) {
                    $play->logo = $request->logo;
                    $response['logo'] = $play->logo;
                }

                if (isset($request->page_turn_way)) {
                    $play->page_turn_way = $request->page_turn_way;
                    $response['page_turn_way'] = $play->page_turn_way;
                }

                if (isset($request->is_cycle)) {
                    $play->is_cycle = $request->is_cycle;
                    $response['is_cycle'] = $play->is_cycle;
                }

                if (isset($request->is_auto)) {
                    $play->is_auto = $request->is_auto;
                    $response['is_auto'] = $play->is_auto;
                }

                if (isset($request->is_share)) {
                    $play->is_share = $request->is_share;
                    $response['is_share'] = $play->is_share;
                }

                if (isset($request->is_template)) {
                    $play->is_template = $request->is_template;
                    $response['is_template'] = $play->is_template;
                }

                if (isset($request->music_url)) {
                    $play->music_url = $request->music_url;
                    $response['music_url'] = $play->music_url;
                }

                $sectionData = json_decode($request->sections, true);

                // 微信分享标题
                if (isset($request->wx_share_title)) {
                    $play->wx_share_title = $request->wx_share_title;
                }
                // 微信分享图片
                if (isset($request->wx_share_image)) {
                    $play->wx_share_image = $request->wx_share_image;
                }
                // 微信分享描述
                if (isset($request->wx_share_description)) {
                    $play->wx_share_description = $request->wx_share_description;
                }

                if ($sectionData && isset($sectionData[0]['properties']['src'])) {
                    $play->first_image = $sectionData[0]['properties']['src'];
                }
                // DB::connection()->enableQueryLog();
                $play->save();
                // $query = DB::getQueryLog();

                // return ['status_code' => 2003, 'data' => $play->id, 'sql' => json_encode($query)];

                // 循环获取此次提交的所有id
                $sectionIds = [];
                foreach ($sectionData as $sectionItem) {
                    if (isset($sectionItem['id'])) {
                        $sectionIds[] = $sectionItem['id'];
                    }
                }

                foreach ($sectionData as $data) {
                    $section = new Section;

                    $responseSection = [];
                    $section->play_id = $play->id;
                    if (isset($data['name'])) {
                        $section->name = $data['name'];
                        $responseSection['name'] = $section->name;
                    }
                    $section->num = $data['num'];
                    $responseSection['num'] = $section->num;

                    $section->properties = json_encode($data['properties']);
                    $responseSection['properties'] = $section->properties;

                    $section->elements = json_encode($data['elements']);
                    $responseSection['elements'] = $section->elements;

                    $section->save();

                    $responseSection['id'] = $section->id;
                    $response['sections'][] = $responseSection;
                }
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();

            throw new StoreResourceFailedException('update error', $validator->errors());
        }

        // 生成该 play 的二维码图片，便于分享
        $qrcodeImagePath = \App\Org\Developer\Helper::makeQrcodeImage('http://thearte.jumpcity.cn/view?id=' . $play->id);
        $play->qrcode_image_url = $qrcodeImagePath;
        $play->save();
        // $result = 
        // if (!$result) {
        //     return JsonReturnInfo::infoFailure('创建失败.');
        // }
        $response['qrcode_image_url'] = $qrcodeImagePath;

        return ['status_code' => 200, 'data' => ['id' => $play->id, 'play' => $response]];
    }

    /**
     * @SWG\Delete(
     *     summary="删除剧本",
     *     path="/play/{id}",
     *     description="用户删除剧本",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="id",
     *         in="path",
     *         description="剧本id",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     * @param $request
     * @param $id
     *
     * @return array
     */
    public function destroy_play(Request $request)
    {
        $play = Play::where(['user_id' => $request->user()->id])->find($request->id);
        if ($play) {
            Section::where(['play_id' => $request->id])->delete();

            $play = Play::where(['user_id' => $request->user()->id])->find($request->id);
            $play->delete();
        } else {
            throw new StoreResourceFailedException('delete error');
        }

        return ['status_code' => 200];
    }

    /**
     * 访问累加
     */
    public function count(Request $request, $id)
    {
        $play = Play::find($id); // 找不到的话 $play 是 null；
        $play->counts++;
        $play->save();
        return ['status_code' => 200];
    }

    // 动画数据
    public function animation() 
    {
        // 添加动画分类信息和数据
        $categoryModels = AnimationCategory::select(['id', 'name'])->get();
        foreach ($categoryModels as $key => $value) {
            $animationModels = Animation::select(['id', 'name', 'classname', 'content'])->where('category_id', $value['id'])->get();
            $categoryModels[$key]['child'] = $animationModels;
        }

        return [
            'status_code' => 200,
            'data' => $categoryModels
        ];
    }
}
